<?php

namespace App\Console\Commands;

use Illuminate\Filesystem\Filesystem;
use Illuminate\Support\Str;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;

class MakeControllerCommand extends BaseCommand
{
    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'create:controller';
    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = "Generate controllers from config/api.*.php";

    /**
     * @var \Illuminate\Filesystem\Filesystem
     */
    protected $files;

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function fire()
    {
        $target = $this->argument('target');
        $this->formatTargets($target);
        $tables = $this->loadTables();
        $resource = $tables[0];

        $meta = parent::getMetaData($resource);
        $primary_key = $meta["primary"];
        $model = $this->to_camel(Str::singular($resource));
        $controller = Str::title(Str::singular($resource));
        $defaultDb = env("DB_DATABASE");
        $data = [
            'catalog' => ($this->getDatabase() == $defaultDb) ? "default" : $this->getDatabase(),
            'resource' => $resource,
            'table' => $resource,
            'class' => $this->to_camel($controller) . "Controller",
            'controller' => $this->to_camel($controller) . "Controller",
            'model_name' => $model,
            'namespace' => 'app\\Http\\Controller',
            'meta' => $meta,
            'primary' => $primary_key,
            'primary_key' => $primary_key
        ];

        $this->putCommonVariables($data);
        $this->doGenerate($data);

    }


    protected function getArguments()
    {
        return [
            ['target', InputArgument::REQUIRED, 'specify the resource name. ']
        ];
    }


    /**
     * @param $item
     */
    protected function doGenerate($item)
    {
        $this->files = new Filesystem();

        $basePath = app()->basePath();
        $filePath = $basePath . "/app/Http/Controllers/" . $item['class'] . ".php";
        if ($this->files->exists($filePath)) {
            echo $filePath . " already exists\n";
        } else {
            $content = view('stubs/controller', $item);
            $this->files->put($filePath, $content);
            echo $filePath . " generated\n";
        }
    }
}